using System;
using System.Collections.Generic;
using System.Linq;

namespace BF
{
    public static class IListExtension
    {
        public static T GetRandomItem<T>(this IList<T> self)
        {
            if (self == null || self.Count == 0)
            {
                return default(T);
            }

            return self[UnityEngine.Random.Range(0, self.Count)];
        }

        public static T GetRandomItem<T>(this IList<T> self, Random random = null)
        {
            if (self == null || self.Count == 0)
            {
                return default(T);
            }

            return self[random.Next(0, self.Count)];
        }


        public static void Shuffle<T>(this IList<T> self, Random random = null)
        {
            if (self == null || self.Count == 0)
            {
                return;
            }
            if (random == null)
            {
                random = new Random();
            }
            //费雪耶兹随机置乱算法
            for (int i = self.Count - 1; i > 0; --i)
            {
                int j = random.Next(0, i + 1);
                T temp = self[i];
                self[i] = self[j];
                self[j] = temp;
            }
        }

        public static IList<T> Swap<T>(this IList<T> self, int x, int y)
        {
            if (self != null && x >= 0 && x < self.Count && y >= 0 && y < self.Count)
            {
                T temp = self[x];
                self[x] = self[y];
                self[y] = temp;
            }
            return self;
        }
    }
}
